package com.bocai.controller;

import com.bocai.bean.*;
import com.bocai.service.IDistributorCashInfoService;
import com.bocai.service.ISalesService;
import com.bocai.service.ITabService;
import com.bocai.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Cemetery on 2018-04-18.
 * 标签管理
 */

@Controller
@RequestMapping("sales")
public class SalesController {
    @Autowired
    private ISalesService salesService;

    @Autowired
    private IDistributorCashInfoService iDistributorCashInfoService;

    @ApiOperation(value = "添加分销商", notes = "增加分销商")
    @RequestMapping(value = "/addSales", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "salesName", dataType = "string", required = true, value = "分销商名称", defaultValue = "唐唐"),
            @ApiImplicitParam(paramType = "query", name = "birthdayTime", dataType = "string", required = true, value = "出生年月", defaultValue = "2018-01-01"),
            @ApiImplicitParam(paramType = "query", name = "sales_sex", dataType = "int", required = true, value = "性别（1，男 0，女）", defaultValue = "0"),
            @ApiImplicitParam(paramType = "query", name = "sales_city", dataType = "string", required = true, value = "城市", defaultValue = "北京"),
            @ApiImplicitParam(paramType = "query", name = "sales_area", dataType = "string", required = true, value = "区域", defaultValue = "北京"),
            @ApiImplicitParam(paramType = "query", name = "salesPhone", dataType = "string", required = true, value = "分销商电话", defaultValue = "18311111"),
            @ApiImplicitParam(paramType = "query", name = "salesEmail", dataType = "string", required = true, value = "邮箱", defaultValue = "18311111@163.com"),
    })
    @ResponseBody
    public ResponseData setTab(String salesName, String salesPhone, String birthdayTime, int sales_sex, String sales_city, String sales_area, String salesEmail) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.CODE_1);
        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{salesName, salesPhone});
        if (ObjUtils.isEmpty(codeEnum)) {
            TSalesUser tSalesUser = new TSalesUser();
            tSalesUser.setSalesName(salesName);
            tSalesUser.setSalesPhone(salesPhone);
            String passWord = MD5Utils.md5Password("123456");
            tSalesUser.setSalesPassword(passWord);
            try {
                tSalesUser.setBirthdayTime(DateUtils.parse(birthdayTime, "yyyy-MM-dd"));
                tSalesUser.setSalesSex(sales_sex);
                tSalesUser.setSalesCity(sales_city);
                tSalesUser.setSalesArea(sales_area);
                tSalesUser.setSalesEmail(salesEmail);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tSalesUser.setCreateTime(new java.util.Date());
            if (salesService.insertSale(tSalesUser) > 0) {
                data.setCodeEnum(CodeEnum.SUCCESS);
                return data;
            }
        } else {
            data.setCodeEnum(CodeEnum.CODE_4);
        }
        return data;
    }

    @ApiOperation(value = "分销商列表", notes = "分销商列表")
    @RequestMapping(value = "/salesList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "salesPhone", dataType = "string", required = false, value = "分销商电话", defaultValue = "18311111"),
    })
    @ResponseBody
    public ResponseData salesList(String salesPhone) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        TSalesUser salesUser = new TSalesUser();
        if (salesPhone != null && salesPhone.trim().length() > 0)
            salesUser.setSalesPhone("%" + salesPhone + "%");
        List<Map<String, Object>> salesLists = salesService.selectSalesList(salesUser);
        List<Map<String, Object>> salesList = salesService.selectSalesList(null);
        Map<String, Object> maps = new HashMap<>();
        double salesMoney = 0;//总佣金
        double outMoneyAll = 0;//已提现佣金
        double inMoneyAll = 0;//待体现佣金

        for (int i = 0; i < salesList.size(); i++) {
            salesMoney = salesMoney + (Double) salesList.get(i).get("backMoney");
            BigDecimal bigOut = (BigDecimal) salesList.get(i).get("outMoney");
            BigDecimal bigIn = (BigDecimal) salesList.get(i).get("salesMoney");

            outMoneyAll += bigOut.doubleValue();
            inMoneyAll += bigIn.doubleValue();
        }
        maps.put("salesCount", salesList.size() + "");
        maps.put("salesMoney", salesMoney + "");
        maps.put("outMoneyAll", outMoneyAll);
        maps.put("inMoneyAll", inMoneyAll);
        maps.put("sales", salesLists);
        data.setResults(maps);
        return data;
    }

    @ApiOperation(value = "分销商会员列表", notes = "会员列表")
    @RequestMapping(value = "/salesUserList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "salesId", dataType = "int", required = true, value = "分销商ID", defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "userPhone", dataType = "string", required = false, value = "用户账号", defaultValue = "15010417787"),
    })
    @ResponseBody
    public ResponseData salesUserList(Integer salesId, String userPhone) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        if (null == salesId || salesId < 0) {
            data.setCodeEnum(CodeEnum.CODE_90002);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("salesId", salesId);
        if (userPhone != null)
            map.put("userPhone", "%" + userPhone + "%");
        data.setResults(salesService.selectSalesUserList(map));
        return data;
    }

    @ApiOperation(value = "充值明细列表", notes = "充值明细列表")
    @RequestMapping(value = "/salesDetail", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", dataType = "int", required = true, value = "用户id", defaultValue = "3"),
    })
    @ResponseBody
    public ResponseData salesDetail(Integer userId) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        if (null == userId || userId < 0) {
            data.setCodeEnum(CodeEnum.CODE_90002);
        }
        data.setResults(salesService.selectSalesDetail(userId));
        return data;
    }


    @ApiOperation(value = "分销商详情", notes = "分销商详情")
    @RequestMapping(value = "/salesDetails", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "salesId", dataType = "int", required = true, value = "分销商ID", defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData salesDetails(Integer salesId) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        if (null == salesId || salesId < 0) {
            data.setCodeEnum(CodeEnum.CODE_90002);
        }
        data.setResults(salesService.selectSalesDetails(salesId));
        return data;
    }




    @ApiOperation(value = "分销商提现记录", notes = "分销商提现记录")
    @RequestMapping(value = "/salesGetMoneyInfo", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "salesId", dataType = "int", required = true, value = "分销商ID", defaultValue = "1"),
    })
    @ResponseBody
    public ResponseData salesGetMoneyInfo(Integer salesId) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        if (null == salesId || salesId < 0) {
            data.setCodeEnum(CodeEnum.CODE_90002);
        }
        data.setResults(salesService.selectOutMoney(salesId));
        return data;
    }

    @ApiOperation(value = "分销商提现 列表", notes = "分销商提现列表")
    @RequestMapping(value = "/salesGetMoneyList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData salesGetMoneyList() {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        data.setResults(salesService.selectMoneys());
        return data;
    }

    @ApiOperation(value = "分销商提现 审核", notes = "通过，不通过")
    @RequestMapping(value = "/updateCheck", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "putForwardId", dataType = "int", required = true, value = "提现id", defaultValue = "1"),
            @ApiImplicitParam(paramType = "query", name = "cashState", dataType = "int", required = true, value = "提现状态2，成功 3，失败", defaultValue = "2"),
    })
    @ResponseBody
    public ResponseData updateCheck(Integer putForwardId, Integer cashState) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        if (null == putForwardId || putForwardId < 0 || cashState < 2 || cashState > 3) {
            data.setCodeEnum(CodeEnum.CODE_90002);
            return data;
        }
        TSalesOutMoneyInfo outMoneyInfo = salesService.selectOutMoneyDetail(putForwardId);  //查询该条提现 记录
        if (outMoneyInfo != null && outMoneyInfo.getCashState() == 1) {
            TSalesOutMoneyInfo moneyInfo = new TSalesOutMoneyInfo();
            moneyInfo.setPutForwardId(putForwardId);
            moneyInfo.setCashState(cashState);
            moneyInfo.setDistributorId(outMoneyInfo.getDistributorId());
            moneyInfo.setEndTime(new Date());
            Integer count = salesService.updateCheck(moneyInfo);   //更改提现状态
            if (count > 0 && cashState == 3) {
                int backCount = salesService.updateBackMoney(outMoneyInfo); //提现失败，退回金额
                if (backCount < 1)
                    data.setCodeEnum(CodeEnum.CODE_60001);
            } else if (count < 1) {
                data.setCodeEnum(CodeEnum.CODE_60001);
            } else
                data.setResults(count);
        } else {
            data.setCodeEnum(CodeEnum.CODE_60001);
        }
        return data;
    }


}
